# -*- coding:utf-8 -*-
#基础函数
import chardet

def read_file(filepath='', encoding='auto'):
    """
    读取文件
    传入：
        filepath    str   文件路径
        encoding    str   编码（auto则尝试自动识别）
    返回：
        res {
            success    bool  是否成功读取
            encoding   str   实际编码
            data       str   解码后的数据或错误信息
        }
    """
    res = {
        'encoding': encoding,
        'data': None,
        'success': False
    }
    with open(filepath, 'rb+') as f:
        data = f.read()
        f.close()
    if data is None:
        res['data'] = "无法读取文件"
        return res
    if encoding == 'auto':
        _res = chardet.detect(data)
        encoding = _res['encoding']
        data = data.decode(encoding)
        res['encoding'] = encoding
        res['data'] = data
        res['success'] = True
    else:
        try:
            data = data.decode(encoding)
            res['data'] = data
            res['success'] = True
        except Exception as e:
            _res = chardet.detect(data)
            _encoding = _res['encoding']
            res['data'] = '''+++++++++++++++++++++++++++++++++++++++++++
[ERROR]{}
+++++++++++++++++++++++++++++++++++++++++++
{}'''.format(str(e), 'it maybe coding by {}'.format(_encoding) if _encoding else 'UNKNOW')
    return res

